package work;

import javax.swing.*;
import java.util.ArrayList;
import java.util.List;

public class GameRule {
    List<int[]> list=new ArrayList<int[]>();
    Window game;

    public GameRule(Window game){
        this.game = game;
    }

    //记录蛇的历史轨迹
    public void setLocation(int x,int y) {
        if(list.size()>1000) {
            list.remove(999);
        }
        int a[] = new int[2];
        a[0]=x;
        a[1]=y;
        list.add(0,a);
    }

    //获取蛇的身体的位置
    public List<int[]> getLocations(){
        List<int[]> locations = new ArrayList<int[]>();
        for(int i =1 ; i<=game.bodyCount ; i++){
            locations.add(list.get(i));
        }
        return locations;
    }

    //获取蛇的尾巴的位置
    public int[] getLocation(){
        int[] location = list.get(game.bodyCount);
        return location;
    }

    //判断蛇的状态
    public void judge(int x,int y,int w,int z){

        if(x<0||y<0||y>game.height-60||x>game.width-160) {
            JOptionPane.showMessageDialog(game, "蛇撞到了墙");
            newGame();
        }
        if(death()) {
            JOptionPane.showMessageDialog(game, "蛇吃到了自己");
            newGame();
        }
        if(x==w&&y==z) {
            addBody();    // 增加蛇的身体
        }
    }

    //移动身体
    public void moveBody(){
        List<int[]> locations = getLocations();
        for(int i=1;i<=game.bodyCount;i++){
            int location[] = locations.get(i-1);
            game.body[i].setBounds(location[0],location[1],10,10);
            game.add(game.body[i]);
        }
    }

    //添加身体
    public  void addBody(){
        game.bodyCount++;
        game.label.setText("分数:"+game.bodyCount);
        int location[] =this.getLocation();
        game.body[game.bodyCount] = new JButton();
        game.body[game.bodyCount].setBounds(location[0],location[1],10,10);
        game.add(game.body[game.bodyCount]);
        game.addFood();
    }

    //判断是否吃到自己
    public boolean death(){
        for(int i=1;i<=game.bodyCount;i++){
            int location[] = list.get(i);
            if(game.x == location[0] && game.y == location[1]){
                return true;
            }
        }
        return false;
    }

    //重新开始游戏
    public void newGame(){
        for(int i=1;i<=game.bodyCount;i++){
            game.remove(game.body[i]);
        }
        game.timer.stop();
        game.bodyCount=0;
        game.keyCount=0;
        game.addFood();
        game.addHead();
        game.a=null;
        game.label.setText("分数："+0);
        game.repaint();
    }

}

